import 'dart:async';
import 'dart:convert';

import 'package:flutter_app/bean/list_app_article_entity.dart';
import 'package:flutter_app/bean/list_dynamic_entity.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/ui/apply/apply/apply_view.dart';
import 'package:flutter_app/ui/apply/apply_detail/apply_detail_view.dart';
import 'package:flutter_app/ui/collect/collect/collect_view.dart';
import 'package:flutter_app/ui/collect/collect_detail2/collect_detail_view.dart';
import 'package:flutter_app/ui/main/main_logic.dart';
import 'package:flutter_app/ui/mine/film/film_detail/film_detail_view.dart';
import 'package:flutter_app/ui/msg/msg_detail/msg_detail_view.dart';
import 'package:flutter_app/ui/news/news/news_view.dart';
import 'package:flutter_app/ui/news/news_detail/news_detail_view.dart';
import 'package:flutter_app/utils/EventBusUtils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/widget/picker/camera_utils.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'home_state.dart';

class HomeLogic extends GetxController {
  final HomeState state = HomeState();
  final mainLogic = Get.find<MainLogic>();

  RefreshController refreshController = RefreshController(initialRefresh: false);

  /// 订阅事件 CollectDetailEvent
  late StreamSubscription<DynamicEvent> _dynamicEvent;

  // 刷新
  void onRefresh() async {
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果失败,使用refreshFailed ()
    postListArticle().then((_) {
      refreshController.refreshCompleted();
    });
    listDynamic().then((_) {
      refreshController.refreshCompleted();
    });
    refreshController.refreshCompleted();
  }

  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    postListArticle();
    listDynamic();

    /// 订阅事件 HomeEvent 处理
    _dynamicEvent = bus.listen((event) {
      listDynamic();
    });
  }

  /// 门户-获取内容分页信息
  Future<void> postListArticle() async {
    Map<String, dynamic> params  = {
      "contentType": "XNYW",
      "isRotation": "",
      "keyword": "",
      "state": ""
    };
    Map<String, dynamic> param = {
      "currentPage": 1,
      'pageSize': 5,
      'param': params
    };
    ResultData resultData = await Api.postListArticle(param);
    if (resultData.isSuccess) {
      state.listAppArticleEntity = ListAppArticleEntity.fromJson(resultData.data['data']);
      update();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 获取效能动态
  Future<void> listDynamic() async {
    Map<String, dynamic> param = {
      "currentPage": 1,
      'pageSize': 5,
      'param': {}
    };
    ResultData resultData = await Api.listDynamic(param);
    if (resultData.isSuccess) {
      List<dynamic> list = jsonDecode(jsonEncode(resultData.data['data']));
      state.listDynamicEntity = list.map((e) => ListDynamicEntity.fromJson(e)).toList();
      update();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 获取值
  List<ListDynamicDynamicVOList>? getListDynamic(String type) {
    List<ListDynamicDynamicVOList>? dynamicDynamicVOList;
    state.listDynamicEntity?.forEach((element) {
      if (element.type == type) {
        dynamicDynamicVOList = element.dynamicVOList;
      }
    });
    return dynamicDynamicVOList;
    // return state.listDynamicEntity?.where((element) => element.type == type).cast<ListDynamicDynamicVOList>().toList();
  }

  // 调用相机 拍照跳转 随手拍 问题上报
  void goToProblemReportPage() {
    CameraUtils().takePictureToPage();
  }

  void goToApplyPage() => Get.to(() => ApplyPage(title: "报名"));

  void goToCollectPage() => Get.to(() => CollectPage(title: "任务采集"));

  void goToNewsPage() => Get.to(() => NewsPage(title: "要闻"));

  // type = 1 随手拍 详情
  void goToFilmDetail(String? id) {
    Get.to(() => FilmDetailPage(title: "随手拍上报记录详情",), arguments: id);
  }

  // type = 2 明察暗访任务（采集）详情
  void goToCollectDetailPage(String? groupId) {
    Get.to(() => CollectDetailPage(title: "任务详情",), arguments: groupId);
  }

  // type = 3 效能通知 详情
  void goToMsgDetailPage(String? id) {
    mainLogic.updateNoticeRead(id).then((_) {
      listDynamic();
    });
    Get.to(() => MsgDetailPage(title: "公告通知",), arguments: id);
  }

  // type = 4 效能活动报名（报名） 详情
  void goToApplyDetailPage(String? id) {
    Get.to(() => ApplyDetailPage(title: "报名详情",), arguments: id);
  }

  // 要闻 详情
  void goToNewsDetailPage(String? id) {
    Get.to(() => NewsDetailPage(title: '要闻详情',), arguments: id);
  }

  @override
  void onClose() {
    super.onClose();
    _dynamicEvent.cancel();
  }
}
